import {getTimeDiffObj} from "./timeDiff";

/*
活动倒计时
 */
class ActivityCountDown {

    constructor(start, end) {
        const now = parseInt(new Date().valueOf() / 1000);
        this.start = start;
        this.end = end;
        if (end < now) {
            this.status = 'end';//活动已结束
            return;
        }
        if (start <= now) {//活动进行中
            this.status = 'start';
            this.seconds = end - now;
            this.afterCountDown();
        } else {
            this.status = 'wait';//活动未开始
            this.seconds = start - now;
            this.beforeCountDown();
        }
        this.timeObj = {}
    }

    /**
     * 活动开始前倒计时
     */
    beforeCountDown() {
        this.djs = setInterval(() => {
            this.seconds--;
            if (this.seconds <= 0) {
                clearInterval(this.djs);
                this.status = 'start';
                const now = parseInt(new Date().valueOf() / 1000);
                this.seconds = this.end - now;

                this.afterCountDown();
            } else {
                this.timeObj = getTimeDiffObj(this.seconds);
            }
        }, 1000);
    }

    /**
     * 活动进行中倒计时
     */
    afterCountDown() {
        this.djs = setInterval(() => {
            this.seconds--;
            if (this.seconds <= 0) {
                clearInterval(this.djs);
                this.status = 'end';
            } else {
                this.timeObj = getTimeDiffObj(this.seconds);
            }
        }, 1000);

    }

}


export {ActivityCountDown}

export default ActivityCountDown;
